<?php


namespace Um\WechatPay;

/**
 * Class PaySignerV2
 *
 * @see     https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=4_3
 * @see     https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/marketing/miniprogram/chapter3_1.shtml
 * @package Um\WechatPay
 */
class PayV2Signer
{
	protected $appKey;

	protected $signData;

	const SIGN_TYPE_MD5 = 'md5';
	const SIGN_TYPE_SHA256 = 'sha256';

	public function __construct(string $appKey)
	{
		$this->appKey = $appKey;
	}

	public function setSignData(array $data)
	{
		ksort($data);
		foreach ($data as $key => $value) {
			if (empty($value) || $key === 'sign')
				continue;
			$this->signData[$key] = $value;
		}
		return $this;
	}

	public function exportSign($signType = self::SIGN_TYPE_MD5)
	{
		if (empty($this->signData)) return '';
		if (empty($this->appKey)) return '';

		$signStr = '';
		foreach ($this->signData as $key => $value) {
			$signStr .= $key . "=" . $value . "&";
		}
		$signStr .= "key={$this->appKey}";

		if($signType == self::SIGN_TYPE_MD5) {
			$sign = strtoupper(md5($signStr));
		} else {
			$sign = strtoupper(hash_hmac('sha256', $signStr, $this->appKey));
		}
		return $sign;
	}
}